import Router from '@koa/router';
import sequelize from '../config/db.js';
import Comment from '../models/Comment.js';
import User from '../models/user.js';
import { auth } from '../middlewares/auth.js';
const router = new Router({ prefix: '/api' });

// 统一的错误响应结构
const errorResponse = (code, message) => ({
  code,
  message,
  data: null
});

// 统一的成功响应结构
const successResponse = (data, meta = null) => ({
  code: 'SUCCESS',
  message: '操作成功',
  data,
  meta
});
// 工具函数：平铺数据转树形
function buildCommentTree(comments) {
  const map = new Map();
  const tree = [];
  comments.forEach(comment => {
    comment.children = [];
    map.set(comment.id, comment);
    if (comment.parent_id === 0) {
      tree.push(comment);
    } else {
      const parent = map.get(comment.parent_id);
      parent.children.push(comment);
    }
  });
  return tree;
}
// GET /api/comments?article_id=1
router.get('/comments', async (ctx) => {
  try {
    const { article_id } = ctx.query;
    const query = `
    SELECT
      comments.id,
      comments.article_id,
      comments.user_id,
      comments.parent_id,
      comments.root_id,
      comments.content,
      comments.depth,
      comments.created_at,
      comments.updated_at,
      comments.is_deleted,
      users.username
    FROM
      comments
    LEFT JOIN
      users
    ON
      comments.user_id = users.id
    WHERE
      comments.article_id = ${article_id}
    ORDER BY
      comments.root_id DESC,
      comments.created_at ASC;
  `;
    const comments = await sequelize.query(query, {
      replacements: { article_id }, // 替换 SQL 中的参数
      type: sequelize.QueryTypes.SELECT, // 返回结果类型为 SELECT
    });
    console.log('%c [ comments ]-68', 'font-size:13px; background:pink; color:#bf2c9f;', comments)
    if (!comments.length) { ctx.body = successResponse([]) }
    else {
      let data = buildCommentTree(comments)
      ctx.body = successResponse(data); // 将平铺数据转为树形结构

    }
  } catch (err) {
    console.error('查询失败:', err);
    ctx.status = 500;
    ctx.body = errorResponse('INTERNAL_ERROR', '服务器内部错误');
  }
});




// POST /api/comments
router.post('/comments', auth, async (ctx) => {
  const { content, article_id, parent_id = 0 } = ctx.request.body;
  // 数据校验
  if (!content) {
    ctx.status = 400;
    ctx.body = errorResponse('CONTENT_REQUIRED', '评论内容不能为空');
    return;
  }
  if (!article_id) {
    ctx.status = 400;
    ctx.body = errorResponse('ARTICLE_ID_REQUIRED', '文章ID不能为空');
    return;
  }
  // 获取父评论信息（如果有）
  let parent = null;
  if (parent_id !== 0) {
    parent = await Comment.findByPk(parent_id);
    if (!parent) errorResponse('PARENT_COMMENT_ERROR', '父评论不存在');
  }

  // 创建新评论
  const comment = await Comment.create({
    content,
    article_id,
    user_id: ctx.state.user.userId,
    parent_id,
    root_id: parent ? parent.root_id : 0, // 若为根评论，后续更新为自身ID
    depth: parent ? parent.depth + 1 : 1
  });
  // console.log('%c [ comment ]-111', 'font-size:13px; background:pink; color:#bf2c9f;', comment.dataValues)
  console.log('%c [ comment ]-111', 'font-size:13px; background:pink; color:#bf2c9f;', comment.dataValues.id)

  const query = `
  SELECT
    comments.id,
    comments.article_id,
    comments.user_id,
    comments.parent_id,
    comments.root_id,
    comments.content,
    comments.depth,
    comments.created_at,
    comments.updated_at,
    comments.is_deleted,
    users.username
  FROM
    comments
  LEFT JOIN
    users
  ON
    comments.user_id = users.id
  WHERE
    comments.article_id = ${article_id}
    AND comments.id = ${comment.dataValues.id}
  ORDER BY
    comments.root_id DESC,
    comments.created_at ASC;
`;
  // 更新 root_id（如果是主评论）
  if (parent_id === 0) {
    comment.root_id = comment.id;
    await comment.save();
  }

  const newComments = await sequelize.query(query, {
    replacements: { article_id }, // 替换 SQL 中的参数
    type: sequelize.QueryTypes.SELECT, // 返回结果类型为 SELECT
  });
  if (newComments.length) {

    ctx.body = successResponse(newComments[0]);
    return
  }
  ctx.body = successResponse({});

});

export default router;